import { LOGOUT, LOGIN, SET_TITLE } from "./action-types"
import { reqLogin, reqLogout } from "@/api"
import { message } from "antd"
import cookies from "@/utils/cookies"

// 登录
export const login = (data, navigate) => async (dispatch) => {
  const { username, password, code, key } = data
  const encrypt_password = password // encrypt(password)
  return new Promise((resolve, reject) => {
    reqLogin({
      grant_type: "password",
      code,
      key,
      username: username,
      password: encrypt_password,
      client_id: "admin",
      client_secret: "123456",
    })
      .then((res) => {
        const { data } = res
        dispatch({
          type: LOGIN,
          data: data.token,
        })
        cookies.set("react-token", data.token)
        cookies.set("refreshToken", data.refreshToken)
        cookies.set("refreshTime", data.expiresIn)
        cookies.set("loginTime", +new Date())
        setTimeout(() => {
          navigate("/admin", {
            replace: true,
          })
        }, 500)
        resolve()
      })
      .catch((error) => {
        reject(error)
      })
  })
}

// 退出登录
export const logout = (navigate) => async (dispatch) => {
  dispatch({
    type: LOGOUT,
    data: {},
  })
  reqLogout().then((res) => {
    // 删除cookie
    cookies.remove("react-token")
    cookies.remove("refreshToken")
    cookies.remove("refreshTime")
    cookies.remove("loginTime")
    // 跳转路由
    message.success(res.message)
    setTimeout(() => {
      navigate("/login")
    }, 500)
  })
}

//  修改路由标题
export const setTitle = (title) => (dispatch) => {
  dispatch({
    type: SET_TITLE,
    data: title,
  })
}
